﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BadHabit.Factory.Controls
{
    /// <summary>
    /// Interaction logic for TailPanel.xaml
    /// </summary>
    public partial class TailPanel : GenericPanel {

        private BadHabit.WPFTools.DelayFilter delayFilter;

        public TailPanel() {
            InitializeComponent();
            delayFilter = new BadHabit.WPFTools.DelayFilter(1, ApplyFilter);
        }

        private void backlogListView_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            Bind();
        }


        /// <summary>
        /// This should overwrited.
        /// </summary>
        /// <returns></returns>
        protected override bool RequestData() {
            Bind();
            return true;
        }
      

        private void Bind() {

            if (!IsSelected)
                return;

            artifactsListBox.IsInFilter = IsInFilter;

            Data.ProjectDataSet.BacklogItemRow item = Helper.GetRowFromRowView<Data.ProjectDataSet.BacklogItemRow>(backlogListView.SelectedItem);
            if (item != null)
                artifactsListBox.BacklogItemUId = item.BacklogItemUId;
            else
                artifactsListBox.BacklogItemUId = null;

            artifactsListBox.LoadArtifacts();            

            LoadItems();
            LoadTasks();
            ApplyFilter();

            
      
        }

        private Data.TaskDataSet.TaskRow taskFilter = null;
        public Data.TaskDataSet.TaskRow TaskFilter {
            get {
                return taskFilter;
            }
            set {
                taskFilter = value;
                if (taskFilter != null) {
                    SelectBacklogItem(taskFilter.BacklogItemUId);
                    taskFilterLabel.Text = taskFilter.TaskId.ToString();
                    taskFilterLabel.Visibility = Visibility.Visible;
                } else {
                    taskFilterLabel.Visibility = Visibility.Collapsed;                    
                }
                
                ApplyFilter();
                
            }
        }

    

        private void LoadItems() {
            Data.TaskDataSet dsTail = new BadHabit.Factory.Data.TaskDataSet();
            Data.ProjectDataSet.BacklogItemRow item = Helper.GetRowFromRowView<Data.ProjectDataSet.BacklogItemRow>(backlogListView.SelectedItem);
            
            
            try {
                if (item == null)
                    dsTail.Merge(Client.Service.RetriveImpactedItemsByProjectUId(DataContextAsProjectDataSet.Project[0].ProjectUId));                
                else
                    dsTail.Merge(Client.Service.RetriveImpactedItemsByBacklogItemUId(item.BacklogItemUId));                
            } catch (Exception ex) {
                Views.Error.ShowError(ex, global::BadHabit.Factory.Windows.Properties.Resources.COULD_NOT_READ_IMPACTED_ITEMS);
            }

            impactedItemsListBox.ItemsSource = dsTail.TaskTailImpactedItem;

        }

        private void LoadItemsByArtifcat() {
            Data.TaskDataSet dsTail = new BadHabit.Factory.Data.TaskDataSet();
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(artifactsListBox.SelectedItem);
            if (tail == null) {
                LoadItems();
                return;
            }

            try {
                dsTail.Merge(Client.Service.RetriveImpactedItemsByTailUId(tail.TaskTailUId));
            } catch (Exception ex) {
                Views.Error.ShowError(ex, global::BadHabit.Factory.Windows.Properties.Resources.COULD_NOT_READ_IMPACTED_ITEMS);
            }

            impactedItemsListBox.ItemsSource = dsTail.TaskTailImpactedItem;

        }


        private void LoadTasks() {
            Data.TaskDataSet dsTask = new BadHabit.Factory.Data.TaskDataSet();
            Data.ProjectDataSet.BacklogItemRow item = Helper.GetRowFromRowView<Data.ProjectDataSet.BacklogItemRow>(backlogListView.SelectedItem);
            

            try {
                if (item == null)
                    dsTask.Merge(Client.Service.RetriveTasksByTailedProjectUId(DataContextAsProjectDataSet.Project[0].ProjectUId));
                else
                    dsTask.Merge(Client.Service.RetriveTasksByTailedBacklogItemUId(item.BacklogItemUId));
            } catch (Exception ex) {
                Views.Error.ShowError(ex, global::BadHabit.Factory.Windows.Properties.Resources.COULD_NOT_READ_IMPACTED_TASKS);
            }

            taskListView.ItemsSource = dsTask.TaskResume;
            

        }

        private void LoadTasksByArtifact() {
            Data.TaskDataSet dsTask = new BadHabit.Factory.Data.TaskDataSet();
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(artifactsListBox.SelectedItem);
            if (tail == null) {
                LoadTasks();
                return;
            }

            try {
                dsTask.Merge(Client.Service.RetriveTasksByArtifactPath(tail.ArtifactPath));
            } catch (Exception ex) {
                Views.Error.ShowError(ex, global::BadHabit.Factory.Windows.Properties.Resources.COULD_NOT_READ_IMPACTED_TASKS);
            }

            taskListView.ItemsSource = dsTask.TaskResume;

        }


        private bool IsInFilter(object obj) {
            System.Data.DataRowView tail = obj as System.Data.DataRowView;
            if (tail == null)
                return false;

            if (!tail["ArtifactName"].ToString().ToUpper().Contains(searchTextBox.Text.ToUpper()))
                return false;

            if (TaskFilter != null) {
                if (!tail["TaskUId"].ToString().Equals(TaskFilter.TaskUId))
                    return false;
            }

            return true;

        }

        private void searchTextBox_TextChanged(object sender, TextChangedEventArgs e) {
            delayFilter.StartFilter();
        }

        private void ApplyFilter() {
            ListCollectionView view = artifactsListBox.ItemsSource as ListCollectionView;
            if (view == null)
                return;            
            view.Refresh();            
        }


        public void SelectBacklogItem(string backlogItemUId) {
            foreach(System.Data.DataRowView item in backlogListView.Items) {
                if(item["BacklogItemUId"].Equals(backlogItemUId)) {
                    
                    backlogListView.SelectedItem = item;
                    backlogListView.ScrollIntoView(item);
                    return;
                }
            }
                    
        }

        private void cleanFilterMenuItem_Click(object sender, RoutedEventArgs e) {
            TaskFilter = null;
        }

       
     
        private void artifactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            LoadTasksByArtifact();
            LoadItemsByArtifcat();
        }


        

    }
}
